package com.leo.chapter06;

import java.util.concurrent.*;

/**
 * 每个图片建立一个独立任务，并在线程池中执行
 * 从CompletionService中take的每一个图片都是下载完成的，完成之后立即显示，性能更好
 * @author xuexiaolei
 * @version 2017年10月15日
 */
public class Renderer {
    private final ExecutorService exec;

    public Renderer(ExecutorService exec) {
        this.exec = exec;
    }

    void renderPage(CharSequence source){
        //下载图片
        final ImageInfo[] imageInfos = scanForImageInfo(source);
        CompletionService<ImageData> completionService = new ExecutorCompletionService<ImageData>(exec);
        for (final ImageInfo imageInfo : imageInfos){//每个图片下载均建立一个task
            completionService.submit(new Callable<ImageData>() {
                @Override public ImageData call() throws Exception {
                    return imageInfo.downloadImage();
                }
            });
        }

        //渲染文字
        renderText(source);

        //渲染图片
        try {
            for (int i = 0; i < imageInfos.length; i++) {
                Future<ImageData> f = completionService.take();
                ImageData imageData = f.get();
                renderImage(imageData);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();//设置线程的中断状态
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void renderImage(ImageData data) {
        System.out.println("正在渲染图片");
    }

    private ImageInfo[] scanForImageInfo(CharSequence source) {
        return new ImageInfo[]{};
    }

    private void renderText(CharSequence source) {
        System.out.println("正在渲染文字");
    }

    class ImageData{}
    class ImageInfo{
        public ImageData downloadImage(){
            System.out.println("下载图片中");
            try {
                Thread.sleep(1000);//很浪费时间的
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new ImageData();
        }
    }
}
